package cn.bonoon.handler.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

import cn.bonoon.handler.RedirectToUserHome;
import cn.bonoon.kernel.AccessAuthorityResolver;
import cn.bonoon.kernel.menus.ModuleDefinition;
import cn.bonoon.kernel.security.LogonUser;

/**
 * <pre>
 * 默认的情况；
 * 
 * 以后需要加入根据当前用户自己定义的首页进入，即自定义的系统进入点
 * </pre>
 * @author jackson
 *
 */
public class DefaultLoginSuccessRedirect implements RedirectToUserHome, ApplicationContextAware{

	private ApplicationContext applicationContext;
	
	public final void setApplicationContext(ApplicationContext context) throws BeansException {
		applicationContext = context;
	}

	private String targetUrl;

	@Override
	public String redirectUrl(HttpServletRequest request, HttpServletResponse response, LogonUser logonUser) {

        if (StringUtils.hasText(targetUrl)) return targetUrl;
        
    	AccessAuthorityResolver resolver = AccessAuthorityResolver.valueOf(applicationContext, logonUser);
    	
    	if(logonUser.isSuper()) return resolver.plaformUrl();
    	
    	if(logonUser.allowAccess()){

			for(ModuleDefinition module : resolver.resolveModules()){
				//只取第一个
				return module.getEndpoint();
			}
		}
		return resolver.homeUrl();
	}
	
	public void setTargetUrl(String targetUrl) {
		this.targetUrl = targetUrl;
	}
}
